package com.ug.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ug.common.constant.CommonConstants;
import com.ug.common.enums.ErrorCode;
import com.ug.common.exception.SystemException;
import com.ug.common.id.SnowFlakeFactory;
import com.ug.system.entity.SysRole;
import com.ug.system.entity.SysRoleMenu;
import com.ug.system.entity.dto.RoleMenuDto;
import com.ug.system.mapper.SysRoleMapper;
import com.ug.system.mapper.SysRoleMenuMapper;
import com.ug.system.service.SysRoleMenuService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @Author LY
 * @create 2024/7/16 17:55
 * @Description 角色菜单服务实现层
 */
@Service
@RequiredArgsConstructor
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements SysRoleMenuService {

    private final Logger logger = LoggerFactory.getLogger(SysRoleMenuServiceImpl.class);
    private final SysRoleMapper roleMapper;

    @Override
    public List<SysRoleMenu> getMenuByRoleId(Long roleId) {
        LambdaQueryWrapper<SysRoleMenu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRoleMenu::getRoleId, roleId);
        return baseMapper.selectList(wrapper);
    }

    @Override
    public void editMenuRoleByRoleId(RoleMenuDto roleMenuDto) {
        Long roleId = roleMenuDto.getRoleId();
        //  获取当前角色信息
        SysRole role = roleMapper.selectById(roleId);
        if (role == null){
            throw new SystemException(ErrorCode.NOT_ROLE_ERROR);
        }
        if (CommonConstants.ROLE_ADMIN.equals(role.getRoleCode())){
            throw new SystemException(ErrorCode.ROOT_ROLE_ERROR);
        }
        //  1先清空之前角色的所有菜单
        deleteByRoleId(roleId);
        //  2遍历所有的菜单
        if (!CollectionUtils.isEmpty(roleMenuDto.getMenuIds())){
            roleMenuDto.getMenuIds().forEach(menuId -> {
                SysRoleMenu roleMenu = new SysRoleMenu();
                roleMenu.setId(SnowFlakeFactory.getSnowFlakeFromCache().nextId());
                roleMenu.setMenuId(menuId);
                roleMenu.setRoleId(roleId);
                baseMapper.insert(roleMenu);
            });
        }
    }

    @Override
    public void deleteByRoleId(Long roleId) {
        LambdaQueryWrapper<SysRoleMenu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRoleMenu::getRoleId, roleId);
        baseMapper.delete(wrapper);
    }
}
